package metro.milano;

import java.util.ArrayList;
import java.util.List;

import metro.milano.util.Commons;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Maps extends MapActivity {

	private static final int PIXELS_WIDTH = 220;
	private static final int PIXELS_HEIGHT = 80;
	protected static final double DISTANCE_LIMIT = 5000;

	private MapView mMapView;
	private MapController mMapController;
	private LinearLayout mNoteBaloon;
	private List<Overlay> mMapOverlays;
	private double mLatitude;
	private double mLongitude;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maps);

		mLatitude = getIntent().getDoubleExtra("latitude", 0);
		mLongitude = getIntent().getDoubleExtra("longitude", 0);
		// TEST
//		mLatitude = 45.460371;
//		mLongitude = 9.182854;
		// END

		mMapView = (MapView) findViewById(R.id.maps);
		mMapView.setBuiltInZoomControls(true);
		mMapController = mMapView.getController();

		LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mNoteBaloon = (LinearLayout) layoutInflater.inflate(R.layout.baloon_layout, null);

		mMapOverlays = mMapView.getOverlays();
		drawIcon();

	}

	private void drawIcon() {

		GeoPoint p = new GeoPoint((int) (mLatitude * 1E6), (int) (mLongitude * 1E6));

		mMapController.animateTo(p);
		mMapController.setZoom(15);
		mMapView.invalidate();

		Drawable drawable = this.getResources().getDrawable(R.drawable.ic_maps_indicator_current_position);
		final CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(drawable, this);

		OverlayItem storeOverlay = new OverlayItem(p, getString(R.string.my_position), "");

		itemizedOverlay.addOverlay((OverlayItem) storeOverlay);

		mMapOverlays.add(itemizedOverlay);

		JSONArray mMetroStation = Commons.getInstance().getMetroStation();

		Drawable drawableMetro1 = this.getResources().getDrawable(R.drawable.linea_1_icon);
		final CustomItemizedOverlay itemizedOverlayMetro1 = new CustomItemizedOverlay(drawableMetro1, this);

		Drawable drawableMetro2 = this.getResources().getDrawable(R.drawable.linea_2_icon);
		final CustomItemizedOverlay itemizedOverlayMetro2 = new CustomItemizedOverlay(drawableMetro2, this);

		Drawable drawableMetro3 = this.getResources().getDrawable(R.drawable.linea_3_icon);
		final CustomItemizedOverlay itemizedOverlayMetro3 = new CustomItemizedOverlay(drawableMetro3, this);

		Drawable drawableMetro4 = this.getResources().getDrawable(R.drawable.icona_metro);
		final CustomItemizedOverlay itemizedOverlayMetro4 = new CustomItemizedOverlay(drawableMetro4, this);

		Drawable drawableMetro5 = this.getResources().getDrawable(R.drawable.linea_5_icon);
		final CustomItemizedOverlay itemizedOverlayMetro5 = new CustomItemizedOverlay(drawableMetro5, this);

		
		for (int i = 0; i < mMetroStation.length(); i++) {
			GeoPoint p1 = null;
			JSONObject o = null;
			try {
				o = (JSONObject) mMetroStation.get(i);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			try {
				p1 = new GeoPoint((int) (Double.parseDouble(o.getString("latitude")) * 1E6), (int) (Double.parseDouble(o
						.getString("longitude")) * 1E6));

				OverlayItem storeOverlay3 = new OverlayItem(p1, o.getString("metro"), "Linea " + o.getString("metroID"));
				if (o.getString("metroID").equals("M1")) {
					itemizedOverlayMetro1.addOverlay((OverlayItem) storeOverlay3);
				} else if (o.getString("metroID").equals("M2")) {
					itemizedOverlayMetro2.addOverlay((OverlayItem) storeOverlay3);
				} else if (o.getString("metroID").equals("M3")) {
					itemizedOverlayMetro3.addOverlay((OverlayItem) storeOverlay3);
				} else if (o.getString("metroID").equals("M5")) {
					itemizedOverlayMetro5.addOverlay((OverlayItem) storeOverlay3);
				}else {
					itemizedOverlayMetro4.addOverlay((OverlayItem) storeOverlay3);
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		mMapOverlays.add(itemizedOverlayMetro1);
		mMapOverlays.add(itemizedOverlayMetro2);
		mMapOverlays.add(itemizedOverlayMetro3);
		mMapOverlays.add(itemizedOverlayMetro5);
		mMapOverlays.add(itemizedOverlayMetro4);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {

		private ArrayList<OverlayItem> mMapOverlays = new ArrayList<OverlayItem>();
		private LinearLayout mDetail;

		public CustomItemizedOverlay(Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
		}

		public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
			this(defaultMarker);
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mMapOverlays.get(i);
		}

		@Override
		public int size() {
			return mMapOverlays.size();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
		}

		@Override
		protected boolean onTap(int index) {

			final OverlayItem item = mMapOverlays.get(index);
			mMapView.removeView(mNoteBaloon);
			mNoteBaloon.setVisibility(View.VISIBLE);

			mMapController.animateTo(item.getPoint());

			float d = Maps.this.getResources().getDisplayMetrics().density;
			int pixelsWidthMod = (int) (PIXELS_WIDTH * d);
			int pixelsHeightMod = (int) (PIXELS_HEIGHT * d);

			final GeoPoint geoPoint = new GeoPoint(item.getPoint().getLatitudeE6(), item.getPoint().getLongitudeE6());
			mMapView.addView(mNoteBaloon, new MapView.LayoutParams(pixelsWidthMod, pixelsHeightMod, geoPoint, 0, -40,
					MapView.LayoutParams.BOTTOM_CENTER));
			mMapView.setEnabled(true);

			mDetail = (LinearLayout) findViewById(R.id.path);

			ImageButton imageButton = (ImageButton) findViewById(R.id.imageDistance);
			TextView textView = (TextView) findViewById(R.id.textDistance);

			TextView title = (TextView) findViewById(R.id.note_label);
			title.setText(item.getTitle());
			((TextView) mNoteBaloon.findViewById(R.id.note_text)).setText(item.getSnippet());
			if (item.getTitle().equals(getString(R.string.my_position))) {
				textView.setVisibility(View.GONE);
				imageButton.setVisibility(View.GONE);
			} else {
				// mDetail.setVisibility(View.VISIBLE);
				textView.setVisibility(View.VISIBLE);
				imageButton.setVisibility(View.VISIBLE);
			}
			final Location myLocation = new Location("");
			myLocation.setLatitude(mLatitude);
			myLocation.setLongitude(mLongitude);

			mDetail.setOnClickListener(new OnClickListener() {

				private double distance;

				public void onClick(View v) {
					try {

						Location locationA = new Location("");
						locationA.setLatitude(geoPoint.getLatitudeE6() / 1E6);
						locationA.setLongitude(geoPoint.getLongitudeE6() / 1E6);
						distance = locationA.distanceTo(myLocation);

						String uri = "http://maps.google.com/maps?saddr=" + mLatitude + "," + mLongitude + "&daddr="
								+ geoPoint.getLatitudeE6() / 1E6 + "," + geoPoint.getLongitudeE6() / 1E6;
						if (distance < DISTANCE_LIMIT) {
							uri += "&dirflg=w";
						}
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
						startActivity(intent);

					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
				}
			});

			imageButton.setOnClickListener(new OnClickListener() {
				private double distance;

				public void onClick(View v) {

					try {

						Location locationA = new Location("");
						locationA.setLatitude(geoPoint.getLatitudeE6() / 1E6);
						locationA.setLongitude(geoPoint.getLongitudeE6() / 1E6);
						distance = locationA.distanceTo(myLocation);

						String uri = "http://maps.google.com/maps?saddr=" + mLatitude + "," + mLongitude + "&daddr="
								+ geoPoint.getLatitudeE6() / 1E6 + "," + geoPoint.getLongitudeE6() / 1E6;
						if (distance < DISTANCE_LIMIT) {
							uri += "&dirflg=w";
						}
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
						startActivity(intent);

					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
				}

			});

			return true;
		}

		public void addOverlay(OverlayItem overlay) {
			mMapOverlays.add(overlay);
			populate();
		}

		public void clear() {
			mMapOverlays.clear();
			mMapView.removeAllViews();
			populate();
		}

	}

}